﻿package net.wangit.view.unit.sum;

import java.math.BigDecimal;

import net.wangit.Element;
import net.wangit.context.LocalContext;
import net.wangit.util.Checker;
import net.wangit.util.NumberUtil;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.element.component.ProgressBarElement;


public class SumValue {

	private int rowIndex;
	private String groupValue;
	private boolean percent;
	private BigDecimal value;
	private BigDecimal base;

	public SumValue() {
		rowIndex = -1;
		percent = false;
		value = new BigDecimal("0");
		base = new BigDecimal("0");
	}

	public int getRowIndex() {
		return rowIndex;
	}

	public void setRowIndex(int index) {
		rowIndex = index;
	}

	public String getGroupValue() {
		return groupValue;
	}

	public void setGroupValue(String groupValue) {
		this.groupValue = groupValue;
	}

	public String getValue(Element element) {
		if (base.doubleValue() == 0.0D)
			return value.toString();
		String result = Double.toString(NumberUtil.format2(value.doubleValue()
				/ base.doubleValue()));
		if (element instanceof ProgressBarElement) {
			StringBuffer html = new StringBuffer();
			net.wangit.context.ActionContext ac = LocalContext
					.getLocalContext().getActionContext();
			Element temp = ((ElementComponent) element).cloneElement(ac, null);
			temp.setShowMode(1);
			temp.setDefaultValue(result);
			temp.write(ac, html, 0, null);
			result = html.toString();
		} else if (percent)
			result = (new StringBuilder(String.valueOf(Integer
					.toString(NumberUtil
							.format0(Double.parseDouble(result) * 100D)))))
					.append("%").toString();
		return result;
	}

	public void sum(String value) {
		this.value = this.value.add(new BigDecimal(getValue(value)));
	}

	public void sum(String value, String base) {
		this.value = this.value.add(new BigDecimal(getValue(value)));
		this.base = this.base.add(new BigDecimal(getValue(base)));
	}

	private String getValue(String value) {
		return Checker.isEmpty(value) ? "0" : value;
	}

	public void setPercent(boolean percent) {
		this.percent = percent;
	}
}
